package com.example.synccenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.synccenter.entity.IdentitySourceEntity;
import com.example.synccenter.event.IdentitySourceConfigEvent;
import com.example.synccenter.event.IdentitySourceEventPublisher;
import com.example.synccenter.identitysource.core.IdentitySourceEventListener;
import com.example.synccenter.service.IdentitySourceService;
import com.example.synccenter.service.IdentitySourceValidationService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 身份源管理控制器，提供身份源的CRUD和状态管理API。
 * 支持身份源的创建、更新、删除、启用/禁用和手动同步等操作。
 */
@Slf4j
@RestController
@RequestMapping("/api/identity-source")
@RequiredArgsConstructor
public class IdentitySourceController {
    private final IdentitySourceService identitySourceService;
    private final IdentitySourceValidationService validationService;
    private final IdentitySourceEventPublisher eventPublisher;
    private final IdentitySourceEventListener eventListener;
    private final ObjectMapper objectMapper;

    /**
     * 获取所有身份源列表
     * @return 身份源列表
     */
    @GetMapping
    public List<IdentitySourceEntity> list() {
        return identitySourceService.list();
    }

    /**
     * 根据ID获取身份源
     * @param id 身份源ID
     * @return 身份源实体
     */
    @GetMapping("/{id}")
    public ResponseEntity<IdentitySourceEntity> getById(@PathVariable String id) {
        IdentitySourceEntity entity = identitySourceService.getById(id);
        return entity != null ? ResponseEntity.ok(entity) : ResponseEntity.notFound().build();
    }

    /**
     * 创建新的身份源
     * @param entity 身份源实体
     * @return 创建结果
     */
    @PostMapping
    public ResponseEntity<?> create(@RequestBody IdentitySourceEntity entity) {
        try {
            // 将config对象转换为JSON字符串
            if (entity.getConfig() != null && !(entity.getConfig() instanceof String)) {
                entity.setConfig(objectMapper.writeValueAsString(entity.getConfig()));
            }
            
            // 验证配置
            validationService.validateConfig(entity);
            // 保存配置
            identitySourceService.save(entity);
            // 发布事件
            eventPublisher.publishConfigEvent(entity.getId(), entity.getType(), IdentitySourceConfigEvent.EventType.CREATE);
            return ResponseEntity.ok(entity);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", e.getMessage()
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", "创建身份源失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 更新身份源
     * @param id 身份源ID
     * @param entity 身份源实体
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> update(@PathVariable String id, @RequestBody IdentitySourceEntity entity) {
        try {
            // 获取原有的身份源信息
            IdentitySourceEntity existingEntity = identitySourceService.getById(id);
            if (existingEntity == null) {
                return ResponseEntity.notFound().build();
            }

            // 验证配置
            validationService.validateConfig(entity);
            
            // 更新配置
            entity.setId(id);
            identitySourceService.updateById(entity);

            // 处理enabled状态变化
            if (existingEntity.getEnabled() != entity.getEnabled()) {
                if (entity.getEnabled()) {
                    // 如果是从禁用变为启用，发送ENABLE事件
                    eventPublisher.publishConfigEvent(id, entity.getType(), IdentitySourceConfigEvent.EventType.ENABLE);
                } else {
                    // 如果是从启用变为禁用，发送DISABLE事件
                    eventPublisher.publishConfigEvent(id, entity.getType(), IdentitySourceConfigEvent.EventType.DISABLE);
                }
            } else {
                // 如果enabled状态没有变化，但其他配置发生变化，发送UPDATE事件
                eventPublisher.publishConfigEvent(id, entity.getType(), IdentitySourceConfigEvent.EventType.UPDATE);
            }

            return ResponseEntity.ok(entity);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", e.getMessage()
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", "更新身份源失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 删除身份源
     * @param id 身份源ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable String id) {
        try {
            IdentitySourceEntity entity = identitySourceService.getById(id);
            if (entity == null) {
                return ResponseEntity.notFound().build();
            }
            // 发布事件
            eventPublisher.publishConfigEvent(id, entity.getType(), IdentitySourceConfigEvent.EventType.DELETE);
            // 删除配置
            identitySourceService.removeById(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", "删除身份源失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 启用身份源
     * @param id 身份源ID
     * @return 启用结果
     */
    @PostMapping("/{id}/enable")
    public ResponseEntity<?> enable(@PathVariable String id) {
        try {
            IdentitySourceEntity entity = identitySourceService.getById(id);
            if (entity == null) {
                return ResponseEntity.notFound().build();
            }
            if (entity.getEnabled()){
                return ResponseEntity.badRequest().body(Map.of("status", "error", "message", "身份源已启用"));
            }
            entity.setEnabled(true);
            identitySourceService.updateById(entity);
            // 发布事件
            eventPublisher.publishConfigEvent(id, entity.getType(), IdentitySourceConfigEvent.EventType.ENABLE);
            return ResponseEntity.ok(Map.of("status", "success", "message", "身份源已启用"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", "启用身份源失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 禁用身份源
     * @param id 身份源ID
     * @return 禁用结果
     */
    @PostMapping("/{id}/disable")
    public ResponseEntity<?> disable(@PathVariable String id) {
        try {
            IdentitySourceEntity entity = identitySourceService.getById(id);
            if (entity == null) {
                return ResponseEntity.notFound().build();
            }
            if (!entity.getEnabled()) {
                return ResponseEntity.badRequest().body(Map.of("status", "error", "message", "身份源未启用"));
            }
            entity.setEnabled(false);
            identitySourceService.updateById(entity);
            // 发布事件
            eventPublisher.publishConfigEvent(id, entity.getType(), IdentitySourceConfigEvent.EventType.DISABLE);
            return ResponseEntity.ok(Map.of("status", "success", "message", "身份源已禁用"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", "禁用身份源失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 手动触发身份源同步
     * @param id 身份源ID
     * @return 触发结果
     */
    @PostMapping("/{id}/sync")
    public ResponseEntity<?> manualSync(@PathVariable String id) {
        try {
            IdentitySourceEntity entity = identitySourceService.getById(id);
            if (entity == null) {
                return ResponseEntity.notFound().build();
            }
            if (!entity.getEnabled()) {
                return ResponseEntity.badRequest().body(Map.of("status", "error", "message", "身份源未启用"));
            }
            // 使用事件监听器触发同步
            eventListener.sync(id);
            return ResponseEntity.ok(Map.of("status", "success", "message", "同步任务已触发"));
        } catch (Exception e) {
            log.error("触发同步任务失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", "触发同步任务失败: " + e.getMessage()
            ));
        }
    }
} 